import { defineStore } from 'pinia';
import { store } from '/@/store';
// import { useI18n } from '/@/hooks/web/useI18n';
import { useUserStore } from './user';
import { useAppStoreWithOut } from './app';
import { toRaw } from 'vue';
import { transformObjToRoute, flatMultiLevelRoutes, addSlashToRouteComponent } from '/@/router/helper/routeHelper';
import { transformRouteToMenu } from '/@/router/helper/menuHelper';
import projectSetting from '/@/settings/projectSetting';
import { PermissionModeEnum } from '/@/enums/appEnum';
import { asyncRoutes } from '/@/router/routes';
import { ERROR_LOG_ROUTE, PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { filter } from '/@/utils/helper/treeHelper';
import { getMenuList } from '/@/api/sys/menu';
import { getPermCode } from '/@/api/sys/user';
// import { useMessage } from '/@/hooks/web/useMessage';
import { PageEnum } from '/@/enums/pageEnum';
export const usePermissionStore = defineStore({
    id: 'app-permission',
    state: () => ({
        permCodeList: [],
        // Whether the route has been dynamically added
        isDynamicAddedRoute: false,
        // To trigger a menu update
        lastBuildMenuTime: 0,
        // Backstage menu list
        backMenuList: [],
        // menu List
        frontMenuList: [],
        authList: [],
        allAuthList: [],
        sysSafeMode: false,
        onlineSubTableAuthMap: {},
    }),
    getters: {
        getPermCodeList() {
            return this.permCodeList;
        },
        getBackMenuList() {
            return this.backMenuList;
        },
        getFrontMenuList() {
            return this.frontMenuList;
        },
        getLastBuildMenuTime() {
            return this.lastBuildMenuTime;
        },
        getIsDynamicAddedRoute() {
            return this.isDynamicAddedRoute;
        },
        //update-begin-author:taoyan date:2022-6-1 for: VUEN-1162 子表按钮没控制
        getOnlineSubTableAuth: (state) => {
            return (code) => state.onlineSubTableAuthMap[code];
        },
        //update-end-author:taoyan date:2022-6-1 for: VUEN-1162 子表按钮没控制
    },
    actions: {
        setPermCodeList(codeList) {
            this.permCodeList = codeList;
        },
        setBackMenuList(list) {
            this.backMenuList = list;
            list?.length > 0 && this.setLastBuildMenuTime();
        },
        setFrontMenuList(list) {
            this.frontMenuList = list;
        },
        setLastBuildMenuTime() {
            this.lastBuildMenuTime = new Date().getTime();
        },
        setDynamicAddedRoute(added) {
            this.isDynamicAddedRoute = added;
        },
        resetState() {
            this.isDynamicAddedRoute = false;
            this.permCodeList = [];
            this.backMenuList = [];
            this.lastBuildMenuTime = 0;
        },
        async changePermissionCode() {
            const systemPermission = await getPermCode();
            const codeList = systemPermission.codeList;
            this.setPermCodeList(codeList);
            this.setAuthData(systemPermission);
        },
        async buildRoutesAction() {
            // const { t } = useI18n();
            const userStore = useUserStore();
            const appStore = useAppStoreWithOut();
            let routes = [];
            const roleList = toRaw(userStore.getRoleList) || [];
            const { permissionMode = projectSetting.permissionMode } = appStore.getProjectConfig;
            const routeFilter = (route) => {
                const { meta } = route;
                const { roles } = meta || {};
                if (!roles)
                    return true;
                return roleList.some((role) => roles.includes(role));
            };
            const routeRemoveIgnoreFilter = (route) => {
                const { meta } = route;
                const { ignoreRoute } = meta || {};
                return !ignoreRoute;
            };
            /**
             * @description 根据设置的首页path，修正routes中的affix标记（固定首页）
             * */
            const patchHomeAffix = (routes) => {
                if (!routes || routes.length === 0)
                    return;
                let homePath = userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
                function patcher(routes, parentPath = '') {
                    if (parentPath)
                        parentPath = parentPath + '/';
                    routes.forEach((route) => {
                        const { path, children, redirect } = route;
                        const currentPath = path.startsWith('/') ? path : parentPath + path;
                        if (currentPath === homePath) {
                            if (redirect) {
                                homePath = route.redirect;
                            }
                            else {
                                route.meta = Object.assign({}, route.meta, { affix: true });
                                throw new Error('end');
                            }
                        }
                        children && children.length > 0 && patcher(children, currentPath);
                    });
                }
                try {
                    patcher(routes);
                }
                catch (e) {
                    // 已处理完毕跳出循环
                }
                return;
            };
            switch (permissionMode) {
                case PermissionModeEnum.ROLE:
                    routes = filter(asyncRoutes, routeFilter);
                    routes = routes.filter(routeFilter);
                    //  将多级路由转换为二级
                    routes = flatMultiLevelRoutes(routes);
                    break;
                case PermissionModeEnum.ROUTE_MAPPING:
                    routes = filter(asyncRoutes, routeFilter);
                    routes = routes.filter(routeFilter);
                    const menuList = transformRouteToMenu(routes, true);
                    routes = filter(routes, routeRemoveIgnoreFilter);
                    routes = routes.filter(routeRemoveIgnoreFilter);
                    menuList.sort((a, b) => {
                        return (a.meta?.orderNo || 0) - (b.meta?.orderNo || 0);
                    });
                    this.setFrontMenuList(menuList);
                    // 将多级路由转换为二级
                    routes = flatMultiLevelRoutes(routes);
                    break;
                // 后台菜单构建
                case PermissionModeEnum.BACK:
                    // const { createWarningModal } = useMessage();
                    // 菜单加载提示
                    // createMessage.loading({
                    //   content: t('sys.app.menuLoading'),
                    //   duration: 1,
                    // });
                    // 从后台获取权限码，
                    // 这个函数可能只需要执行一次，并且实际的项目可以在正确的时间被放置
                    let routeList = [];
                    try {
                        this.changePermissionCode();
                        routeList = (await getMenuList());
                    }
                    catch (error) {
                        console.error(error);
                    }
                    // 组件地址前加斜杠处理  author: lsq date:2021-09-08
                    routeList = addSlashToRouteComponent(routeList);
                    // 动态引入组件
                    routeList = transformObjToRoute(routeList);
                    // 构建后台路由菜单
                    const backMenuList = transformRouteToMenu(routeList);
                    this.setBackMenuList(backMenuList);
                    // 删除meta.ignoreRoute项
                    routeList = filter(routeList, routeRemoveIgnoreFilter);
                    routeList = routeList.filter(routeRemoveIgnoreFilter);
                    routeList = flatMultiLevelRoutes(routeList);
                    routes = [PAGE_NOT_FOUND_ROUTE, ...routeList];
                    break;
            }
            routes.push(ERROR_LOG_ROUTE);
            patchHomeAffix(routes);
            return routes;
        },
        setAuthData(systemPermission) {
            this.authList = systemPermission.auth;
            this.allAuthList = systemPermission.allAuth;
            this.sysSafeMode = systemPermission.sysSafeMode;
        },
        setAuthList(authList) {
            this.authList = authList;
        },
        setAllAuthList(authList) {
            this.allAuthList = authList;
        },
        //update-begin-author:taoyan date:2022-6-1 for: VUEN-1162 子表按钮没控制
        setOnlineSubTableAuth(code, hideBtnList) {
            this.onlineSubTableAuthMap[code] = hideBtnList;
        },
        //update-end-author:taoyan date:2022-6-1 for: VUEN-1162 子表按钮没控制
    },
});
// 需要在设置之外使用
export function usePermissionStoreWithOut() {
    return usePermissionStore(store);
}
